import os

from langchain.tools import Tool
from langchain_community.utilities import SerpAPIWrapper
from langchain_core.tools import tool

#第三方API工具
os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY_ZHIHU"]
os.environ["OPENAI_API_BASE"] = os.environ["OPENAI_API_BASE_ZHIHU"]
os.environ["SERPAPI_API_KEY"] = 'a01032707e956769e459a23034f3bbda54a364b02cb0dd4ab4b6b42800f6d774'

search = SerpAPIWrapper()
tools = [
    Tool.from_function(
        func=search.run,
        name="Search",
        description="useful for when you need to answer questions about current events"
    ),
]


import calendar
import dateutil.parser as parser
from datetime import date

# 自定义工具
@tool("weekday")
def weekday(date_str: str) -> str:
    """Convert date to weekday name"""
    d = parser.parse(date_str)
    return calendar.day_name[d.weekday()]

tools += [weekday]

#获取 Agent提示模板
from langchain import hub
import json

# 下载一个现有的 Prompt 模板
react_prompt = hub.pull("hwchase17/react")
# print(react_prompt.template)


from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent


llm = ChatOpenAI(model_name='gpt-4o', temperature=0, model_kwargs={"seed":23})

# 定义一个 agent: 需要大模型、工具集、和 Prompt 模板
agent = create_react_agent(llm, tools, react_prompt)
# 定义一个执行器：需要 agent 对象 和 工具集
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)

# 执行
agent_executor.invoke({"input": "2024年周杰伦的演唱会星期几"})